<?php

namespace App\Jobs;

use App\Models\ActivityConfig;
use App\Models\InviteAwardLog;
use App\Models\InviteInfo;
use App\Models\JpushMobile;
use App\Models\User;
use App\Models\UserInvitationCode;
use App\Services\UserService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Models\InviteRelationLog;

class InviteQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const WX_INVITE = 1;    // 微信邀请
    const MB_INVITE = 2;    // 手机邀请

    protected $params;

    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $error = [];
        $params = $this->params;

        if(!empty($params)){
            $data = $params['data'];

            // 创建用户队列
            $user_queue = ['action'=>'create_user_code', 'data'=>['uid'=>$data['uid'], 'create_time'=>time()]];
            dispatch((new UserQueue($user_queue))->onQueue('user_queue'));
            
            // 统计业务
            $user_statistics_key = 'flag:user_statistics:day'.date("Ymd", time()).':'.$data['uid'];
            if(empty(Redis::get($user_statistics_key))){
                $expires_in = 24*3600;
                Redis::setex($user_statistics_key, $expires_in, $data['uid']);
                // 新增统计队列
                $user_statisctics = ['action'=>'user_add', 'data'=>['uid'=>$data['uid'], 'create_time'=>time()]];
                dispatch((new StatisticsQueue($user_statisctics))->onQueue('statistics'));
            }

            // 创建用户的邀请结算记录
            $user_invite_settlement = ['action'=>'add_invite_settlement_user', 'data'=>['uid'=>$data['uid']]];
            dispatch((new StatisticsQueue($user_invite_settlement))->onQueue('statistics'));

            if(!isset($params['type']))
                return ['status'=>'error', 'message'=>'参数异常'];

            // 获取活动配置
            $activity_config_arr = $this->get_activity_config();
            try {
                DB::beginTransaction();
                $invite_uid = 0;

                // 查询邀请人信息
                // 邀请码
                if(isset($data['invitation_code']) && !empty($data['invitation_code'])){
                    $uitc_rowd = UserInvitationCode::where([['invitation_code', '=', $data['invitation_code']]])->first();
                    if(!empty($uitc_rowd))
                        $invite_uid = $uitc_rowd->uid;
                }else{
                    // 查询邀请记录
                    $where[] = ['type', '=', $params['type']];
                    $where[] = ['operation_id', '=', $data['operation_id']];
                    switch ($params['type']){
                        case self::MB_INVITE:
                            $where[] = ['create_time', '>=', (time()-24*3600)];
                            break;
                    }
                    // 分享信息
                    $rows = InviteInfo::where($where)->orderBy('create_time', 'desc')->first();
                    if(!empty($rows))
                        $invite_uid = $rows->uid;
                }
                // 注册用户
                $reg_user_rows = user::where([['id', '=', $data['uid']]])->first();
                // 下载时间
                $download_time = strtotime($reg_user_rows->created_at);
                $jpush_mobile_rows = JpushMobile::select(['id','create_time'])->where([['mobile_unique_code', '=', $data['mobile_unique_code']]])->first();
                if(!empty($jpush_mobile_rows))
                    $download_time = $jpush_mobile_rows->create_time;
                $reg_user_rows->download_time = $download_time;

                // 存在分享用户
                if(!empty($invite_uid)){
                    $award_num = 0;
                    $remark = '不符合奖励要求';
                    // 分享用户
                    $user_rows = User::where([['id', '=', $invite_uid]])->first();
                    if(!empty($user_rows)){

                        $relation_id = ','.$user_rows->id.',';
                        if(!empty($user_rows->relation_id))
                            $relation_id = $user_rows->id.',';

                        $reg_user_rows->parent_id = $user_rows->id;
                        $reg_user_rows->relation_id = $relation_id;
                        // 活动有效
                        if(!empty($activity_config_arr) && time() >= $activity_config_arr['start_time'] && time() <= $activity_config_arr['end_time']){
                            $remark = '邀请奖励';
                            $award_num = $activity_config_arr['reward_amount'];
                        }
                        $user_rows->share_num += 1;
                        $user_rows->share_award += $award_num;
                        if(!$user_rows->save())
                            throw new \Exception('更新邀请奖励异常');
                    }

                    $invite_relation_log_data = [
                        'invite_uid' => $invite_uid,
                        'reg_uid' => $data['uid'],
                        'reg_time' => strtotime($reg_user_rows->created_at),
                        'created_at' => time()
                    ];
                    InviteRelationLog::insert($invite_relation_log_data);
                }

                // 更新注册用户 ： 下载时间、分享用户id
                if(!$reg_user_rows->save())
                    throw new \Exception('更新注册用户有误');
                if(!empty($invite_uid)){
                    $ial_rows = InviteAwardLog::where([['reg_uid', '=', $reg_user_rows->id]])->first();
                    if(!empty($ial_rows))
                        throw new \Exception('该账号已完成了奖励');

                    $invite_award_logModel = new InviteAwardLog();
                    $invite_award_logModel->reg_uid = $reg_user_rows->id;
                    $invite_award_logModel->invite_uid = $user_rows->id;
                    $invite_award_logModel->invite_type = $params['type'];
                    $invite_award_logModel->award_num = $award_num;
                    $invite_award_logModel->remark = $remark;
                    $invite_award_logModel->create_time = time();
                    if(!$invite_award_logModel->save())
                        throw new \Exception('新增分享日志有误');
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                // 处理异常,写入Mongodb
                $params = [['type' => 'invite_award', 'status' => 'error', 'params'=> json_encode($params), 'content' => $e->getMessage(), 'created_at' => time2date()]];
                insert_mongodb_log('invite_award', $params);
            }
        }
    }

    /*
     * 获取活动配置
     * */
    protected function get_activity_config()
    {
        $activity_config_arr = [];
        // 获取配置文件
        if(!empty(Redis::get('activity_config'))){
            $activity_config_arr = json_decode(Redis::get('activity_config'), true);
        }else{
            $ac_where[] = ['status', '=', '1'];
            $ac_where[] = ['start_time', '<=', time()];
            $ac_where[] = ['end_time', '>=', time()];
            $ac_rows = ActivityConfig::select()->where($ac_where)->orderBy('updated_at', 'desc')->first();
            if(!empty($ac_rows)){
                $activity_config_arr = $ac_rows->toArray();
                $expires_in = 1*24*3600;
                Redis::setex('activity_config', $expires_in, json_encode($activity_config_arr));
            }
        }
        return $activity_config_arr;
    }

}
